﻿using Meow.Core.Simulation;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;


namespace Meow.Core.Graphics;

/// <summary>
/// Collect rendering info of a directional light.
/// eg: shadow info
/// </summary>
public class DirectionLightInfo : IDisposable
{
    public static int ReferenceShadowSize = 1024;
    public Vector3 Direction;
    public Vector3 Flux;

    public bool Shadow;
    public int ShadowMapSize { get; private set; }
    public RenderTarget2D ShadowMap;
    public C_Camera Camera { get; private set; } 
    public void Dispose()
    {
        ShadowMap?.Dispose();
    }

    /// <summary>
    /// currentView: the viewport which we want to see the shadows
    /// </summary>
    public void UpdateShadowParam(int currentViewWidth, int currentViewHeight, in C_Camera currentViewCamera, GraphicsDeviceManager gdm)
    {
        var size = Math.Max(currentViewWidth, currentViewHeight);
        var shadowMapSize = (int)Math.Min(ReferenceShadowSize, Exts.NextPowerOf2(size));

        if (shadowMapSize < 0)
            return;

        // need to rebuild shadow map
        if (ShadowMapSize != shadowMapSize)
        {
            ShadowMapSize = shadowMapSize;
            ShadowMap?.Dispose();
            ShadowMap = new RenderTarget2D(gdm.GraphicsDevice, ShadowMapSize, ShadowMapSize, true, SurfaceFormat.Single, DepthFormat.Depth16);
        }


    }

    public void Draw(GraphicsDeviceManager gdm)
    {
        gdm.GraphicsDevice.SetRenderTarget(ShadowMap);
        //gdm.GraphicsDevice.Clear(Microsoft.Xna.Framework.Color.Black);
        gdm.GraphicsDevice.Clear(
                    ClearOptions.DepthBuffer,
                    Microsoft.Xna.Framework.Color.Transparent,
                    gdm.GraphicsDevice.Viewport.MaxDepth,
                    0);
    }
}
